<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\PaySaveRecustomer;
use App\Http\Requests\SaveRecustomer;
use App\Http\Requests\StoreRecustomer;
use App\Http\Requests\UpdateRecustomer;
use App\Models\Company;
use App\Models\Companyplan;
use App\Models\Deposit;
use App\Models\Fixfxs;
use App\Models\Oncustomer;
use App\Models\Rechargeway;
use App\Models\Runfxs;
use App\Models\Recustomer;
use App\Models\Reorder;
use App\Models\Store;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\ViewErrorBag;

class RecustomerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


    public function __construct()
    {
        view()->share([
            '_customers' => 'am-in',
            '_recustomer' => 'am-active',

        ]);

    }

//企业首页
    public function index(Request $request)
    {
//return $request;die;
        $where = function ($query) use ($request) {
            //按会员姓名
            if ($request->has('name') and $request->name != '') {
                $search = "%" . $request->name . "%";
                $query->where('name', 'like', $search);
            }
            //按门店
            if($request->has('store_id')and $request->store_id !='-1'){

                $query->where('store_id',$request->store_id);
            }

        };
           //所有门店
        $cates = Store::all();
        $cs = Recustomer::with('store')->where($where)->orderBy('created_at', 'desc')->paginate(20);

        return view('admin.recustomer.index', compact('cs','cates'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    //新增公司页面
    public function create()
    {
        //当前方案
        $plans = Rechargeway::orderBy('sort')->get();
        //所有门店
        $cates = Store::all();
        return view('admin.recustomer.create', compact('plans', 'cates'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    //执行新增
    public function store(StoreRecustomer $request)
    {
        $data = $request->all();
        $plan = Rechargeway::find($request->rechargeway_id);
        //实际金额为方案固有金额加赠送金额
        $data['money'] = $plan['plan_price'] + $plan['add_price'];
        $data['staff_number'] = $plan['go_number'];
        $data['staff_number'] = $plan['go_number'];
        $data['start_at'] = date('Y-m-d H:i:s', time());
        $data['end_at'] = date('Y-m-d H:i:s', time() + 60 * 60 * 24 * 365 * $plan['valid']);
        $data['key']=rand(100000000,999999999);

       $company= Recustomer::create($data);
        $info['name']=$company['name'];
        $info['tel']=$company['linkman_tel'];
        $info['type']=0;
        $info['about']=$plan['plan_name'];
        $info['store_id']=$company['store_id'];
        $info['price']=$plan['plan_price'];
        Companyplan::create($info);



        return redirect('/admin/recustomer')->with('success', '公司开通成功');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    //修改公司基本信息，不包含开通方案
    public function edit($id)
    {
        //全部方案
        $plans = Rechargeway::orderBy('sort')->get();
        //全部门店
        $cates = Store::all();
        //当前公司
        $company = Recustomer::find($id);
        return view('admin.recustomer.edit', compact('company', 'plans', 'cates'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    //执行基本信息修改
    public function update(UpdateRecustomer $request, $id)
    {
        $customer = Recustomer::find($id);
        $customer->update($request->all());
        return redirect('/admin/recustomer')->with('success', '修改成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
//公司续期或更改方案页面
    public function showplan($id)
    {
        //当前公司
        $company = Recustomer::find($id);
        //全部方案
        $plans = Rechargeway::orderBy('sort')->get();
        $end_at = $company->end_at;
//判断公司是否到期
        if (strtotime($end_at) - time() > 0) {
            $type = 1;
        } else {
            $type = 0;
        }

        return view('admin.recustomer.showplan', compact('company', 'plans', 'type'));
    }

//到期续期或更改方案
    public function saveplan(Request $request, $id)
    {
        $company = Recustomer::find($id);
        $plan = Rechargeway::find($request->rechargeway_id);
        //续期充值，原有方案还未到期，且新增方案为同一方案，原有余额保留
        if ($request->rechargeway_id == $company->rechargeway_id && strtotime($company->end_at) > time()) {
            $company->end_at = date('Y-m-d H:i:s', strtotime($company->end_at) + 60 * 60 * 24 * 365 * $plan['valid']);
            $company->money = $company->money + $plan['plan_price'] + $plan['add_price'];
            $company->save();
            $info['name']=$company['name'];
            $info['tel']=$company['linkman_tel'];
            $info['type']=1;
            $info['about']=$plan['plan_name'];
            $info['store_id']=$company['store_id'];
            $info['price']=$plan['plan_price'];
            Companyplan::create($info);
            return redirect('admin/recustomer')->with('success', '续期成功');
        }
        //原有方案还未到期，新增方案为不同方案，原有余额不保留
        if ($request->rechargeway_id != $company->rechargeway_id && strtotime($company->end_at) > time()) {
            $company->rechargeway_id = $request->rechargeway_id;
            $company->start_at = date('Y-m-d H:i:s', time());
            $company->end_at = date('Y-m-d H:i:s', time() + 60 * 60 * 24 * 365 * $plan['valid']);
            $company->staff_number = $plan->go_number;
            $company->money = $plan['plan_price'] + $plan['add_price'];
            $company->save();
            $info['name']=$company['name'];
            $info['tel']=$company['linkman_tel'];
            $info['type']=2;
            $info['about']=$plan['plan_name'];
            $info['store_id']=$company['store_id'];
            $info['price']=$plan['plan_price'];
            Companyplan::create($info);
            return redirect('admin/recustomer')->with('success', '修改方案成功');
        } // 过期的，原有余额不保留
        else {
            $company->rechargeway_id = $request->rechargeway_id;
            $company->start_at = date('Y-m-d H:i:s', time());
            $company->end_at = date('Y-m-d H:i:s', time() + 60 * 60 * 24 * 365 * $plan['valid']);
            $company->staff_number = $plan->go_number;
            $company->money = $plan['plan_price'] + $plan['add_price'];
            $company->save();
            $info['name']=$company['name'];
            $info['tel']=$company['linkman_tel'];
            $info['type']=3;
            $info['about']=$plan['plan_name'];
            $info['store_id']=$company['store_id'];
            $info['price']=$plan['plan_price'];
            Companyplan::create($info);
            return redirect('admin/recustomer')->with('success', '新开方案成功');
        }

    }

    //充值页面
    public function deposit($id)
    {
        $company = Recustomer::find($id);
        return view('admin.recustomer.deposit', compact('company'));
    }

//执行充值，充值只增加余额，其他都不影响
    public function save(Request $request, $id)
    {
        $company = Recustomer::find($id);
        if (strtotime($company->end_at) < time()) {
            return back()->with('success', '当前套餐已过期，不可充值，请重开套餐');
        } else {
            $company->money = $company->money + $request->deposit_number + $request->add_number;
            $company->save();
            $data['type'] = 0;
            $data['statu'] = 1;
            $data['deposit_number'] = $request->deposit_number;
            $data['contro']=$request->contro;
            $data['company_id']=$id;
            $data['store_id']=$company->store_id;
            Deposit::create($data);
            return redirect('admin/recustomer')->with('success', '充值成功');
        }
    }

//待完善，需要判断公司是否有套餐未到期或余额
    public function destroy($id)
    {
        Recustomer::destroy($id);
        return back()->with('success', '删除成功');
    }

    public function change_key(Request $request)
    {
        $company=Company::find($request->id);
        $company->key=rand(100000000,999999999);
        $company->save();
        //更新KEY  所绑定用户解除绑定
        Oncustomer::where('company_id',$request->id)->update(['company_id' => 0]);

    }




    function sendSms(Request $request)
    {
        $company=Company::find($request->id);

        $params = array();

        // *** 需用户填写部分 ***

        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = "LTAIIFpM0R2RQ7fT";
        $accessKeySecret = "MHtvIeadK9k3GUsbnqe9jZesdo9tAp";

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $company['linkman_tel'];


        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = "阿里云短信测试专用";

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = "SMS_118270074";
        $rand = rand(1000, 9999);
        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = Array(
            "code" => $company['key'],

        );
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }
        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        // 此处可能会抛出异常，注意catch
            $params = $this->request(
                $accessKeyId,
                $accessKeySecret,
                "dysmsapi.aliyuncs.com",
                array_merge($params, array(
                    "RegionId" => "cn-hangzhou",
                    "Action" => "SendSms",
                    "Version" => "2017-05-25",
                ))
            // fixme 选填: 启用https
            // ,true
            );

            return 1;

    }







    public function request($accessKeyId, $accessKeySecret, $domain, $params, $security = false)
    {
        $apiParams = array_merge(array(
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }

        $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));

        $signature = $this->encode($sign);

        $url = ($security ? 'https' : 'http') . "://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = $this->fetchContent($url);
            return json_decode($content);
        } catch (\Exception $e) {
            return false;
        }
    }

//手机验证码封装
    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }

//手机验证码封装
    private function fetchContent($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));

        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if ($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }



}
